from graphics import Image
from appuifw2 import query as query2
from appuifw import Text,app,Form,FFormDoubleSpaced,FFormEditModeOnly,note,Canvas,EScreen
from e32 import Ao_lock,drive_list,start_exe,ao_sleep
from os import path as ospath
from codecs import open as openfile
from struct import unpack,pack
from appswitch import kill_app
from sys import path as syspath

app_lock=Ao_lock()
__appname__=u'NetAlarm'
nomeeseguibileserver = 'netalarm_server_0xeaea0000.exe'
settingsfile=u'c:\\data\\others\\%s.cfg'% __appname__
numerotacche=1
numerointervallo=30
inferiore=0
testo=Text()
fid=0
for i in syspath:
	if i.find('resource')!=-1:
		cartellamif='%s\\apps\\' % syspath[fid]
	fid+=1
del fid
splashfile=u'%sNetAlarm GUI_0x%s_svg.mif' % (cartellamif,app.uid()) #Imposto il file di lavoro
#cartella='e:\\python\\'
#splashfile=u'%sNetAlarm GUI.mif' % (cartella)

def impostazioni():
	global numerotacche,numerointervallo
	oldtitolo=app.title
	app.title=u'Impostazioni'
	if ospath.exists(settingsfile):
		readsettings=openfile(settingsfile,'rb').readlines()[0]
		try: oldnumerotacche,oldnumerointervallo=unpack('>hh',readsettings)
		except: oldnumerotacche,oldnumerointervallo=(numerotacche,numerointervallo)
	else: oldnumerotacche,oldnumerointervallo=(numerotacche,numerointervallo)
	data=[
	(
		u'Numero di tacche limite',
		'combo',
		(
		[u'Disattiva',u'1',u'2',u'3'],oldnumerotacche
		)
	),
	(
		u'Intervallo di tempo',
		'number',
		oldnumerointervallo
	)
	]

	flags=FFormDoubleSpaced+FFormEditModeOnly
	f=Form(data,flags)
	f.execute()
	numerotacche=f[0][2][1] #0=0,1=1 ...
	numerointervallo=f[1][2]

	#Salva e Carica Impostazioni
	settings=pack('>hh',numerotacche,numerointervallo)
	f=openfile(settingsfile,'wb')
	f.write(settings)
	f.close()
	riavviare=query2(u'Riavviare il server per applicare i cambiamenti?','query',ok=u'Si',cancel=u'No')
	if riavviare: 
		#Riavvio il server
		dmn_stop(silent=1)
		dmn_start(silent=1)

	app.title=oldtitolo
	app.activate_tab(0)

def handle_tab(index):
    global lb
    if index == 0:
        myhome() # switch to application 1
    elif index == 1:
        impostazioni() # switch to application 2

def exit_key_handler():
	esci=query2(u'Uscire da %s?'% __appname__,'query',ok=u'Si',cancel=u'No')
	if esci: 
		app_lock.signal()
		app.set_exit()

def carica_settings():
	global numerotacche,numerointervallo
	if ospath.exists(settingsfile):
		readsettings=openfile(settingsfile,'rb').readlines()[0]
		try: numerotacche,numerointervallo=unpack('>hh',readsettings)
		except: pass

def dmn_restart(silent=0):
	dmn_stop(silent=silent)
	dmn_start(silent=silent)

def dmn_start(silent=0):
	drives=drive_list()
	percorso=u'\\sys\\bin\\%s'%(nomeeseguibileserver)
	kill_app(u'NetAlarm Server*')
	eseguito=0
	for d in drives:
		try:
			start_exe(u'%s%s'%(d,percorso),'')
			eseguito=1
		except: continue
	if eseguito:
		ao_sleep(0.5)
		if not silent: note(u'Server avviato!','info')
		mymenu.pop(0)
		mymenu.insert(0,restart)
		mymenu.insert(0,stop)
		#mymenu=[stop,restart]
		#app.menu=mymenu
	else: 
		note(u'Impossibile trovare il server!\nProva a reinstallare il programma.','error')

def dmn_stop(silent=0):
	kill_app(u'NetAlarm Server*')
	if not silent: note(u'Server arrestato!','info')
	mymenu.pop(0)
	mymenu.pop(0)
	mymenu.insert(0,start)
	#mymenu=[start]
	#app.menu=mymenu
	
def handle_redraw(rect): canvas.blit(img)

def myhome():
	img.blit(photo)
	app.body=canvas
	canvas.blit(img)
	
#kill_app(u'NetAlarm Server*')
start=(u'Avvia Server',dmn_start)
restart=(u'Riavvia Server',lambda:dmn_restart(silent=1))
stop=(u'Ferma Server',dmn_stop)
#settngs=(u'Impostazioni',impostazioni)
mymenu=[stop,restart]
app.title=__appname__
try: app.orientation='portrait'
except: pass
app.menu=mymenu
app.exit_key_handler=exit_key_handler
carica_settings()
#testo.set(u'Benvenuto in %s.'%app.title)
#testo.read_only = True
canvas=Canvas(event_callback=None,redraw_callback=handle_redraw)
img=Image.new(app.layout(EScreen)[0])
photo=Image.from_icon(splashfile,16384,(canvas.size[0],canvas.size[1]))
app.set_tabs([u"Home", u"Impost."],handle_tab)
myhome()
app_lock.wait()